package wox.lonice.service.reptile.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wox.lonice.dto.wechat.WeArticle;
import wox.lonice.dto.wechat.WeParamArticle;
import wox.lonice.dto.wechat.WeParamPublic;
import wox.lonice.dto.wechat.WePublic;
import wox.lonice.entity.WeArticleInfo;
import wox.lonice.entity.WeInfo;
import wox.lonice.entity.WePublicInfo;
import wox.lonice.service.WeArticleInfoService;
import wox.lonice.service.WeInfoService;
import wox.lonice.service.WePublicInfoService;
import wox.lonice.service.reptile.ReptileService;
import wox.lonice.utis.BeanUtil;
import wox.lonice.utis.HttpUtil;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class ReptileServiceImpl implements ReptileService {
    private static final Logger logger = LoggerFactory.getLogger(ReptileService.class);

    private static final String publicUrl = "https://mp.weixin.qq.com/cgi-bin/searchbiz";
    private static final String articleUrl = "https://mp.weixin.qq.com/cgi-bin/appmsg";
    private static final String mbArticleUrl = "https://mp.weixin.qq.com/mp/profile_ext";
    private static final String readArticleUrl = "https://mp.weixin.qq.com/mp/readtemplate";

    @Autowired
    private WeInfoService weInfoService;

    @Autowired
    private WePublicInfoService wePublicInfoService;

    @Autowired
    private WeArticleInfoService weArticleInfoService;

    public static void main(String[] args){
        String cookie = "devicetype=iOS12.2; lang=zh_CN; pass_ticket=c/TXeRgh3Kj0mJUx32t9104nuYt5+pEc8J4Vtp7jz5qWybkPKi30gL6KxIejVM5K; version=1700042b; wap_sid2=CLX//cYCElxfeXc5WEV6TFYzSzVpaGlpMUprdlBTY3RYMHZBN0ZEejZEeHpqYm5mT0pnWlgxN0Z3a0dFRWllVExSMWpEYTE5ajZfaU0wdmtPZzRsOGhPUWxVOFZMX1VEQUFBfjC+sI3oBTgNQJVO; wxuin=685735861; pgv_pvid=5306156241; ua_id=IsdaXiPH9Dg0TmhAAAAAAEKik35l7Uo497H-tgaJPyc=; eas_sid=y1x5S5g4O453m1h7z7g5Y2A3W3";

        Map<String, Object> readParamMap = Maps.newHashMap();
        readParamMap.put("t", "pages/video_ad_iframe");
        System.out.println(HttpUtil.sendCookieGet(cookie, readArticleUrl, BeanUtil.getUrlParamsByMap(readParamMap), HttpUtil.iPhoneUserAgent));



        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("action", "getmsg");
        paramMap.put("__biz", "MjM5NjcxNzUxNg==");
        paramMap.put("f", "json");
        paramMap.put("is_ok", 1);
        paramMap.put("pass_ticket", "c/TXeRgh3Kj0mJUx32t9104nuYt5+pEc8J4Vtp7jz5qWybkPKi30gL6KxIejVM5K");
        paramMap.put("appmsg_token", "1013_Ga9LqY9xFz6iIamqUqNS9BaNqIXqg-VHa4P9vg~~");
        paramMap.put("offset", 1);
        paramMap.put("count", 10);

        String publicResult = HttpUtil.sendCookieGet(cookie, mbArticleUrl, BeanUtil.getUrlParamsByMap(paramMap), HttpUtil.iPhoneUserAgent);
        JSONObject publicJsonObject = JSONObject.parseObject(publicResult);
        System.out.println(publicJsonObject);







    }

    @Override
    public void timeGetPublic() {
        List<WeInfo> weInfos = weInfoService.getInfo();
        WeInfo weInfo = weInfos.get(0);

        String[] weQueryArray = weInfo.getWeQuery().split(",");
        for (String weQuery : weQueryArray) {
            try {
                BigDecimal total = this.getPublic(weInfo, weQuery, 0);
                Integer begin = total.divide(BigDecimal.TEN, 0, BigDecimal.ROUND_UP).intValue();
                for (int i = 1; i <= begin; i++) {
                    try {
                        Thread.sleep(60000);
                        this.getPublic(weInfo, weQuery, i);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getLocalizedMessage());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getLocalizedMessage());
            }
        }
    }

    @Override
    public void timeGetArticle() {
        List<WeInfo> weInfos = weInfoService.getInfo();
        WeInfo weInfo = weInfos.get(0);

        List<WePublicInfo> wePublicInfos = wePublicInfoService.selectByAll();
        if (CollectionUtil.isNotEmpty(wePublicInfos)) {
            wePublicInfos.parallelStream().forEach(wePublicInfo -> {
                try {
                    BigDecimal total = this.getArticle(weInfo, wePublicInfo, 0);
                    if (total.compareTo(BigDecimal.ZERO) != 0) {
                        Integer begin = total.divide(BigDecimal.TEN, 0, BigDecimal.ROUND_UP).intValue();
                        for (int i = 1; i <= begin; i++) {
                            try {
                                Thread.sleep(60000);
                                this.getArticle(weInfo, wePublicInfo, i);
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.error(e.getLocalizedMessage());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getLocalizedMessage());
                }
            });
        }
    }

    /**
     * 获取所有公众号信息
     *
     * @param weInfo
     * @param weQuery
     * @param begin
     * @return
     */
    private BigDecimal getPublic(WeInfo weInfo, String weQuery, Integer begin) {
        WeParamPublic weParamPublic = new WeParamPublic();
        weParamPublic.setAction("search_biz").setToken(weInfo.getWeToken())
                .setRandom(Math.random()).setQuery(weQuery).setBegin(begin);
        //bean 转化 map   map转化url get参数
        String param = BeanUtil.getUrlParamsByMap(BeanUtil.bean2Map(weParamPublic));
        //请求参数
        String publicResult = HttpUtil.sendCookieGet(weInfo.getWeCookie(), publicUrl, param, HttpUtil.macUserAgent);
        JSONObject publicJsonObject = JSONObject.parseObject(publicResult);
        if ("ok".equalsIgnoreCase(publicJsonObject.getJSONObject("base_resp").getString("err_msg"))) {
            JSONArray publicJsonArray = publicJsonObject.getJSONArray("list");
            List<WePublic> wePublics = publicJsonArray.toJavaList(WePublic.class);
            List<WePublicInfo> wePublicInfos = Lists.newArrayList();
            wePublics.forEach(wePublic -> wePublicInfos.add(wePublic.returnEntity()));
            logger.info(JSONObject.toJSONString(wePublicInfos));
            //保存数据
            wePublicInfoService.saveAll(wePublicInfos);
            return new BigDecimal(publicJsonObject.getInteger("total"));
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取对应公众号中所有历史文章
     *
     * @param weInfo
     * @param wePublicInfo
     * @param begin
     * @return
     */
    private BigDecimal getArticle(WeInfo weInfo, WePublicInfo wePublicInfo, Integer begin) {
        WeParamArticle weParamArticle = new WeParamArticle();
        weParamArticle.setFakeid(wePublicInfo.getFakeid()).setType(9)
                .setAction("list_ex").setToken(weInfo.getWeToken())
                .setRandom(Math.random()).setQuery("").setBegin(begin);
        //bean 转化 map   map转化url get参数
        String param = BeanUtil.getUrlParamsByMap(BeanUtil.bean2Map(weParamArticle));
        //请求参数
        String articleResult = HttpUtil.sendCookieGet(weInfo.getWeCookie(), articleUrl, param, HttpUtil.macUserAgent);
        JSONObject articleJsonObject = JSONObject.parseObject(articleResult);
        if ("ok".equalsIgnoreCase(articleJsonObject.getJSONObject("base_resp").getString("err_msg"))) {
            JSONArray articleJsonArray = articleJsonObject.getJSONArray("app_msg_list");
            List<WeArticle> weArticles = articleJsonArray.toJavaList(WeArticle.class);
            List<WeArticleInfo> weArticleInfos = Lists.newArrayList();
            weArticles.forEach(weArticle -> weArticleInfos.add(weArticle.returnEntity()));
            logger.info(JSONObject.toJSONString(weArticles));
            //保存数据
            weArticleInfoService.saveAll(weArticleInfos);
            return new BigDecimal(articleJsonObject.getInteger("total"));
        }
        return BigDecimal.ZERO;
    }
}
